<template>
  <!-- 授权用户 -->
  <el-dialog
    title="选择用户"
    :visible.sync="visible"
    width="1200px"
    top="5vh"
    append-to-body
  >
    <el-row :gutter="20">
      <el-col :span="6">
        <el-scrollbar style="height: 480px">
          <el-tree
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          />
        </el-scrollbar>
      </el-col>
      <el-col :span="18">
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
        >
          <el-form-item label="账号名称" prop="userName">
            <el-input
              v-model="queryParams.userName"
              placeholder="请输入用户名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="手机号码" prop="phonenumber">
            <el-input
              v-model="queryParams.phonenumber"
              placeholder="请输入手机号码"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
            <el-button type="primary" @click="handleSelectUser"
              >确 定</el-button
            >
          </el-form-item>
        </el-form>
        <el-row>
          <el-table
            :row-style="{ height: '35px' }"
            :cell-style="{ padding: '0px' }"
            @row-click="clickRow"
            ref="table"
            :data="userList"
            @selection-change="handleSelectionChange"
            height="395px"
            :class="{ 'no-multiple': !isMultiple }"
          >
            <el-table-column
              type="selection"
              width="50"
              align="center"
            ></el-table-column>
            <el-table-column
              label="序号"
              type="index"
              :index="indexMethod"
              width="60"
            />
            <el-table-column
              label="账号名称"
              prop="userName"
              :show-overflow-tooltip="true"
              align="center"
              width="200"
            />
            <el-table-column
              label="用户姓名"
              prop="nickName"
              :show-overflow-tooltip="true"
              align="center"
              width="150"
            />
            <el-table-column
              label="职位"
              prop="position"
              :show-overflow-tooltip="true"
              align="center"
              width="80"
            />
            <el-table-column
              label="手机"
              prop="phonenumber"
              :show-overflow-tooltip="true"
              align="center"
              width="120"
            />
            <el-table-column
              label="创建时间"
              align="center"
              prop="createTime"
              width="150"
            >
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-if="isActOrQues !== 1"
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
          <pagination
            v-if="isActOrQues === 1"
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getListByOrgId"
          />
        </el-row>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import {
  unallocatedUserList,
  authUserSelectAll,
  getDataAuthUser,
  selectDataAuthUser,
  roleMenuList,
} from "@/api/system/role";
import { deptTreeSelect, treeEle } from "@/api/system/user";
import { listUser, listByOrgId } from "@/api/system/user";
import { addView } from "@/api/system/view";
export default {
  dicts: ["sys_normal_disable"],
  props: {
    // 角色编号
    roleId: {
      type: [Number, String],
      default: "",
    },
    menuId: {
      type: [Number, String],
      default: "",
    },
    sign: {
      type: [Number, String],
      default: "",
    },
    userId: {
      type: [Number, String],
      default: "",
    },
    //0多选 1单选
    type: {
      type: [Number, String],
      default: "0",
    },
    //是否是问卷或者活动选择本公司的用户
    isActOrQues: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 遮罩层
      visible: false,
      deptOptions: undefined,
      // 选中数组值
      userIds: [],
      userName: "",
      nickName: "",
      //职务
      position: "",
      //选中的用户名
      userNames: [],
      deptNames: [],
      deptIds: [],
      nickNames: [],
      // 总条数
      total: 0,
      // 未授权用户数据
      userList: [],
      phone: "",
      isMultiple: true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 15,
        menuId: undefined,
        roleId: undefined,
        deptId: null,
        userName: undefined,
        phonenumber: undefined,
      },
      selectionList: [],
      selectedUserId: this.userId,
    };
  },
  created() {
    this.getDeptTree();
  },
  methods: {
    //序号展示
    indexMethod(index) {
      return (
        (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1
      );
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.handleQuery();
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      if (this.isActOrQues === 1) {
        deptTreeSelect({ isOrg: 1 }).then(response => {
          this.deptOptions = response.data;
        });
      } else {
        deptTreeSelect().then(response => {
          this.deptOptions = response.data;
        });
      }
    },
    /**
     * 查询指定公司的部门下拉树结构
     */
    getDeptTreeByOrgId() {
      treeEle().then(res => {
        this.deptOptions = res.data;
      });
    },
    // 显示弹框
    show() {
      this.queryParams.roleId = this.roleId;
      if (this.isActOrQues === 1) {
        this.getListByOrgId();
      } else {
        this.getList();
      }
      this.visible = true;
    },
    clickRow(row) {
      this.$refs.table.toggleRowSelection(row);
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      if (selection.length == 0) {
        this.userIds = [];
        this.userNames = [];
        this.selectionList = [];
      } else {
        this.selectionList = selection.length - 1;
        if (this.type == "1") {
          //单选
          if (selection.length > 1) {
            this.$refs.table.clearSelection();
            this.$refs.table.toggleRowSelection(
              selection[selection.length - 1]
            );
          }
          this.userName = selection[0].userName;
          this.selectedUserId = selection[0].userId;
          this.phone = selection[0].phonenumber;
          this.nickName = selection[0].nickName;
          this.position = selection[0].position;
        }
        if (this.type == "0") {
          //多选
          this.userIds = selection.map(item => item.userId);
          this.userNames = selection.map(item => item.userName);
          this.deptIds = selection.map(item => item.dept.deptId);
          this.deptNames = selection.map(item => item.dept.deptName);
          this.nickNames = selection.map(item => item.nickName);
        }
      }
    },
    /** 选择授权用户操作 */
    handleSelectUser() {
      console.log(this.selectionList);
      const roleId = this.queryParams.roleId;
      const userIds = this.userIds.join(",");
      const userNames = this.userNames.join(",");
      const nickNames = this.nickNames.join(",");
      if (this.type == "0") {
        //多选
        if (this.sign == "1" && this.selectionList.length == 0) {
          this.$modal.msgError("请选择要分配的用户");
          return;
        } else if (this.sign == "" && this.selectionList.length == 0) {
          this.$modal.msgError("请选择要分配的用户");
          return;
        } else if (this.sign == "0" && this.selectionList.length == 0) {
          this.$modal.msgError("请选择要分配的用户");
          return;
        } else {
          this.visible = false;
          this.$emit(
            "ok",
            this.userIds,
            this.userNames,
            this.deptIds,
            this.deptNames,
            this.nickNames
          );
        }
        if (this.sign == "") {
          authUserSelectAll({ roleId: roleId, userIds: userIds }).then(res => {
            this.$modal.msgSuccess(res.msg);
            if (res.code === 200) {
              this.visible = false;
              this.$emit("ok", userIds);
            }
          });
        }
      } else if (this.type == "1") {
        //单选
        if (this.sign == "1" && this.selectionList.length == 0) {
          this.$modal.msgError("请选择用户");
          return;
        } else if (this.sign == "2" && this.selectionList.length == 0) {
          this.$modal.msgError("请选择用户");
          return;
        } else {
          this.visible = false;
          this.$emit(
            "ok",
            this.selectedUserId,
            this.userName,
            this.phone,
            this.position,
            this.nickName
          );
        }
      } else {
        this.visible = false;
        var data = {
          roleId: this.roleId,
          viewUserIds: this.userIds,
          userId: this.selectedUserId,
        };

        addView(data).then(response => {
          this.$emit("selectUser", this.userIds, this.userNames);
        });
      }
    },
    getListByOrgId() {
      listByOrgId(this.queryParams).then(res => {
        console.log(res);
        this.userList = res.rows;
        this.total = res.total;
        this.loading = false;
      });
    },
    // 查询表数据
    getList() {
      //单选
      if (this.type == "1") {
        this.isMultiple = false;
      }
      if (this.sign == undefined || this.sign == "") {
        unallocatedUserList(this.queryParams).then(res => {
          this.userList = res.rows;
          this.total = res.total;
        });
      }
      //用户信息选择
      else if (this.sign == "1") {
        listUser(this.queryParams).then(response => {
          this.userList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      } else if (this.sign == "2") {
        this.queryParams.menuId = this.menuId;
        roleMenuList(this.queryParams).then(response => {
          this.userList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      } else {
        getDataAuthUser(this.roleId, this.selectedUserId).then(res => {
          this.userList = res.rows;
          this.total = res.total;
          this.toggleSelection(this.userList);
        });
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    //默认勾选
    toggleSelection(obj) {
      selectDataAuthUser(this.roleId, this.selectedUserId).then(response => {
        let data = response.data;
        if (data.length != 0) {
          data.forEach(row => {
            obj.forEach(data => {
              if (data.userId == row.userId) {
                this.$refs.table.toggleRowSelection(data);
              }
            });
          });
        }
      });
    },
  },
};
</script>

<style scoped lang="scss">
.no-multiple {
  // 隐藏多选
  ::v-deep .el-table__header-wrapper .el-checkbox {
    display: none;
  }
}
</style>
